/*
 * Copyright (c) 2007, Olof Naessen and Per Larsson
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 *
 *    * Redistributions of source code must retain the above copyright notice, 
 *      this list of conditions and the following disclaimer.
 *    * Redistributions in binary form must reproduce the above copyright notice, 
 *      this list of conditions and the following disclaimer in the documentation 
 *      and/or other materials provided with the distribution.
 *    * Neither the name of the Darkbits nor the names of its contributors may be 
 *      used to endorse or promote products derived from this software without 
 *      specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <allegro.h>
#include <string>
#include <iostream>
#include <sstream>

#include "game.hpp"
#include "timer.hpp"
#include "resourcehandler.hpp"
#include "levelhandler.hpp"
#include "music.hpp"
#include "fading.hpp"
#include <cmath>

Game::Game()
{
	allegro_init();
	install_keyboard();
	
	set_window_title("Darkbits - B.A.L.L.Z.");

	int driver = GFX_AUTODETECT_FULLSCREEN;
	set_color_depth(32);
	if (set_gfx_mode(driver, 640, 480, 0, 0) < 0) {
		set_color_depth(24);
		if (set_gfx_mode(driver, 640, 480, 0, 0) < 0) {
			set_color_depth(16);
			if (set_gfx_mode(driver, 640, 480, 0, 0) < 0) {
				set_color_depth(15);
				if (set_gfx_mode(driver, 640, 480, 0, 0) < 0) {
					throw std::string("Unable to set graphics mode");
				}
			}
		}
	}
	
	initTimer();
	install_sound(DIGI_AUTODETECT, MIDI_NONE, NULL);
	initMusic();

	level = new Level();
	state = MENU;
	fadeRequested = false;

    initGui();
}

void Game::initGui()
{
    mGui = new gcn::Gui();
    mGui->addGlobalKeyListener(this);
    mAllegroGraphics = new gcn::AllegroGraphics();
    mAllegroImageLoader = new gcn::AllegroImageLoader();
    mAllegroInput = new gcn::AllegroInput();

    mGui->setGraphics(mAllegroGraphics);
    mGui->setInput(mAllegroInput);
    gcn::Image::setImageLoader(mAllegroImageLoader);

    mImageFont = new gcn::ImageFont(ResourceHandler::getInstance()->getRealFilename("fontsmall.bmp"), 32, 126);
	mImageFont->setGlyphSpacing(-1);
    gcn::Widget::setGlobalFont(mImageFont);

    mTop = new gcn::Container();
    mTop->setSize(320, 240);
    mTop->setOpaque(false);
    mGui->setTop(mTop);

    mTopBackgroundImage = gcn::Image::load(ResourceHandler::getInstance()->getRealFilename("menubackground.bmp"));
    mTopBackgroundIcon = new gcn::Icon(mTopBackgroundImage);
    mTop->add(mTopBackgroundIcon);

    mBallzLogoImage = gcn::Image::load(ResourceHandler::getInstance()->getRealFilename("ballzlogo.bmp"));
    mBallzLogoIcon = new gcn::Icon(mBallzLogoImage);
    mTop->add(mBallzLogoIcon, 0, 10);

    mMainMenuContainer = new gcn::Container();
    mMainMenuContainer->setSize(320, 240);
    mMainMenuContainer->setOpaque(false);
    mTop->add(mMainMenuContainer);

    mMainMenuListModel = new MainMenuListModel();
    mMainMenuListBox = new BallzListBox();
    mMainMenuListBox->setListModel(mMainMenuListModel);
    mMainMenuListBox->setTabOutEnabled(false);
    mMainMenuListBox->setSelected(0);
    mMainMenuContainer->add(mMainMenuListBox, 125, 150);
    mMainMenuListBox->requestFocus();
    mMainMenuListBox->addActionListener(this);


    mCreditsContainer = new gcn::Container();
    mCreditsContainer->setSize(320, 240);
    mCreditsContainer->setOpaque(false);
    mCreditsContainer->setVisible(false);
    mTop->add(mCreditsContainer);

    mOlofImage = gcn::Image::load(ResourceHandler::getInstance()->getRealFilename("olof.bmp"));
    mOlofIcon = new gcn::Icon(mOlofImage);
    mCreditsContainer->add(mOlofIcon, 80, 95);

    mOlofLabel = new gcn::Label("OLOF NAESSEN");
    mCreditsContainer->add(mOlofLabel, 80, 165);

    mPerImage = gcn::Image::load(ResourceHandler::getInstance()->getRealFilename("per.bmp"));
    mPerIcon = new gcn::Icon(mPerImage);
    mCreditsContainer->add(mPerIcon, 170, 95);

    mPerLabel = new gcn::Label("PER LARSSON");
    mCreditsContainer->add(mPerLabel, 170, 165);

    mCreditsText = new gcn::TextBox("We would like to thank Marcus Matern and Tomas Almgren\n"
                                    "for helping out with making levels. Finally we would like\n"
                                    "to thank Per's girlfriend Johanna for feeding us and putting\n"
                                    "up with the whole idea of making this game in Per's and\n"
                                    "Johanna's apartment.");
    mCreditsText->setOpaque(false);
    mCreditsText->setBorderSize(0);
    mCreditsContainer->add(mCreditsText, 40, 180);

    mLevelsContainer = new gcn::Container();
    mLevelsContainer->setSize(320, 240);
    mLevelsContainer->setOpaque(false);
    mLevelsContainer->setVisible(false);
    mTop->add(mLevelsContainer);

    mLevelSelector = new LevelSelector();
    mLevelSelector->setTabOutEnabled(false);
    mLevelSelector->setSelected(0);
    mLevelSelector->addActionListener(this);
  
    mLevelSelectorScrollArea = new BallzScrollArea();
    mLevelSelectorScrollArea->setSize(310, 88);
    mLevelSelectorScrollArea->setContent(mLevelSelector);
    mLevelsContainer->add(mLevelSelectorScrollArea, 5, 140);

    mCollectedStars = new gcn::Label("Total ~ collected: 0");
    mLevelsContainer->add(mCollectedStars, 115, 120);

    mInfoText = new gcn::TextBox("Team Darkbits Tins 07\n"
                                 "     http://darkbits.org\n"
                                       "           Version 1.0");
    mInfoTextFont = new gcn::ImageFont(ResourceHandler::getInstance()->getRealFilename("fontsmallgrey.bmp"), 32, 126);
    mInfoTextFont->setGlyphSpacing(-1);
    mInfoText->setFont(mInfoTextFont);
    mInfoText->setOpaque(false);
    mInfoText->setBorderSize(0);
    mMainMenuContainer->add(mInfoText, 110, 200);
}

Game::~Game() 
{
    LevelHandler::getInstance()->save();
    LevelHandler::getInstance()->destroy();
    ResourceHandler::getInstance()->destroy();
  
    delete mCreditsText;
    delete mCollectedStars;

    delete mTopBackgroundImage;
    delete mTopBackgroundIcon;

    delete mInfoTextFont;
    delete mInfoText;

    delete mLevelSelector;
    delete mLevelsContainer;

    delete mPerLabel;
    delete mPerIcon;
    delete mPerImage;
    delete mOlofLabel;
    delete mOlofIcon;
    delete mOlofImage;
    delete mCreditsContainer;

    delete mMainMenuListBox;
    delete mMainMenuListModel;
    delete mMainMenuContainer;

	delete mTop;
    delete mImageFont;
    delete mAllegroInput;
    delete mAllegroImageLoader;
    delete mAllegroGraphics;
    delete mGui;
    delete level;

}

void Game::logic() 
{
	pollMusic();

	switch (state) 
    {
	    case LEVEL:	
            if (level->isCompleted())
            {
                int completedLevel = LevelHandler::getInstance()->getCurrentLevel();
                LevelModel* completedLevelModel = LevelHandler::getInstance()->getLevel(completedLevel);

                if (completedLevelModel->numberOfCollectedStars < level->getCollectedStars())
                {
                    completedLevelModel->numberOfCollectedStars = level->getCollectedStars();
                }

                if (completedLevelModel->bestTime > level->getTime()
                    || completedLevelModel->bestTime == -1)
                {
                    completedLevelModel->bestTime = level->getTime();
                }

				requestFade();
                state = MENU;
            }
			else if (level->isFailed()) 
			{
				requestFade();
				state = MENU;
			}
            else
            {
                level->logic();
            }
            break;
        case MENU:
            {
            mGui->logic();
            std::string str;
            std::ostringstream stars(str);
            stars << "Total ~ collected: " << LevelHandler::getInstance()->getStarsCollected();
            mCollectedStars->setCaption(stars.str());
            mCollectedStars->adjustSize();
            break;
            }
	    default:
		    break;
	}

	if (key[KEY_Q]) {
		state = EXIT;
	}
}

void Game::keyPressed(gcn::KeyEvent &keyEvent)
{
    if (keyEvent.getKey().getValue() == gcn::Key::ESCAPE)
    {
        if (mCreditsContainer->isVisible())
        {
            mCreditsContainer->setVisible(false);
            mMainMenuContainer->setVisible(true);
            mMainMenuListBox->requestFocus();
           
        }
        else if (mLevelsContainer->isVisible())
        {
            mLevelsContainer->setVisible(false);
            mMainMenuContainer->setVisible(true);
            mMainMenuListBox->requestFocus();
        }
        else
        {
            state = EXIT;
        }
    }
}

void Game::action(const gcn::ActionEvent& actionEvent)
{
    if (actionEvent.getSource() == mMainMenuListBox)
    {
        if (mMainMenuListBox->getSelected() == 0)
        {
            mMainMenuContainer->setVisible(false);
            mLevelsContainer->setVisible(true);
            mLevelSelector->requestFocus();
        }
        else if (mMainMenuListBox->getSelected() == 1)
        {
            mMainMenuContainer->setVisible(false);
            mCreditsContainer->setVisible(true);
        }
    }
    else if (actionEvent.getSource() == mLevelSelector)
    {
        LevelHandler::getInstance()->setCurrentLevel(mLevelSelector->getSelected());
        LevelModel* levelModel = LevelHandler::getInstance()->getLevel(mLevelSelector->getSelected());

        if (levelModel->starsCollectedUntilUnlocked <= LevelHandler::getInstance()->getStarsCollected())
        {
            level->load(levelModel->mapfile);
            state = LEVEL;
        }
    }
}

void Game::draw(BITMAP *buffer) {
	clear_to_color(buffer, makecol(64, 64, 64));

	switch (state) {
	case MENU:
        mAllegroGraphics->setTarget(buffer);
        mGui->draw();
		break;
	case LEVEL:
		level->draw(buffer);
		break;
	default:
		break;
	}
}

void Game::run()
{
	BITMAP *buffer = create_bitmap(320, 240);

	playMusic(ResourceHandler::getInstance()->getRealFilename("splash.xm"));

    drawSplashScreen(buffer);

	playMusic(ResourceHandler::getInstance()->getRealFilename("finalman-ballz_on_fire.xm"));

	long frame = getTick();
	int graphicframes = 0;
	int second = getTick() / TICKS_PER_SECOND;

	while (state != EXIT) {
		logic();

		if (fadeRequested) {
			fadeOut(buffer, rand() % MAX_FADE_TYPE);
			frame = getTick();
			clear_keybuf();
			fadeRequested = false;
		}

		if (getTick() - frame > 20) {
			frame = getTick();
		}

		frame++;

		if (frame > getTick())
		{
			acquire_bitmap(buffer);
			draw(buffer);
			release_bitmap(buffer);
			stretch_blit(buffer, screen, 0, 0, 320, 240, 0, 0, 640, 480);
			graphicframes++;
		}

		while (frame > getTick()) {
			rest(1);
		}

		if (second != getTick() / TICKS_PER_SECOND) {			
			//std::cout << "FPS: " << graphicframes << std::endl;
			second = getTick() / TICKS_PER_SECOND;
			graphicframes = 0;
		}
	}

	destroy_bitmap(buffer);
}

void Game::drawSplashScreen(BITMAP* dest)
{
    BITMAP* darkbitsLogo = ResourceHandler::getInstance()->getBitmap("darkbitslogo_by_haiko.bmp");
   
    long startTime = getTick();
	int dt = 0;
    while (dt < 200)
    {
		pollMusic();
		dt = getTick() - startTime;
        clear_to_color(dest, makecol(255,255,255));
        
        if (dt > 50 && dt <= 100)
        {
			float l = ((100 - dt) * (100 - dt)) / (50.0 * 50.0);
			int w = darkbitsLogo->w * (1 + 20 * l);
			int h = (darkbitsLogo->h * darkbitsLogo->w) / w;

            masked_stretch_blit(darkbitsLogo, 
                                dest, 
                                0, 
                                0, 
                                darkbitsLogo->w,
                                darkbitsLogo->h,
                                160 - w / 2, 
                                120 - h / 2,
                                w,
                                h);
        }

		if (dt > 100)
        {
			int w = darkbitsLogo->w;
			int h = (darkbitsLogo->h * darkbitsLogo->w) / w;
            masked_stretch_blit(darkbitsLogo, 
                                dest, 
                                0, 
                                0, 
                                darkbitsLogo->w,
                                darkbitsLogo->h,
                                160 - w / 2, 
                                120 - h / 2,
                                w,
                                h);
        }

        stretch_blit(dest, screen, 0, 0, 320, 240, 0, 0, 640, 480);
    }
}

void Game::requestFade() {
	fadeRequested = true;
}
